package com.yantong.controller;


import com.yantong.service.CentreService;
import com.yantong.annotation.Log;
import com.yantong.constant.PayStatus;
import com.yantong.constant.PermisFlag;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.MD5Utils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.pojo.SysRole;
import com.yantong.utils.SysUser;
import com.yantong.pojo.vo.OrderProductVo;
import com.yantong.service.RoleService;
import com.yantong.service.UserService;
import com.yantong.service.MemberService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author kanghaixin
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
	private String prefix="system/user";
	@Autowired
	private UserService userService;
    @Autowired
    private RoleService roleService;
	@Autowired
	private CentreService centreService;
	@Autowired
	private MemberService memberService;
	private Logger logger = LoggerFactory.getLogger(UserController.class);

	@RequiresPermissions("sys:user:user")
	@GetMapping()
	public String user(Model model) {
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/user";
	}


    /**
     * 个人信息页面
     * @param model
     * @return
     */
    @GetMapping("/personal")
    public String personal(Model model) {
        model.addAttribute("user",userService.getUserById(getUserId()));
		model.addAttribute("loginInfo", userService.getPreLoginLog(getUserId()));
		model.addAttribute("account", userService.getAccountInfo());
        return prefix + "/personal";
    }

	/**
	 * 商户详情页面
	 * @param model
	 * @return
	 */
	@GetMapping("/centre")
    @RequiresPermissions("index:centre:centre")
    public String centre(Model model) {
    	model.addAttribute("centre", centreService.getByKey(getUserCentreId()));
    	model.addAttribute("rate", centreService.getRateByCentreId(getUserCentreId()));
    	model.addAttribute("amount", centreService.getAmountByCentreId(getUserCentreId()));
    	model.addAttribute("startDt",userService.getDefaultTime(getUserCentreId()).get("startDt").toString());
    	model.addAttribute("endDt",userService.getDefaultTime(getUserCentreId()).get("endDt").toString());
    	//model.addAttribute("money", userService.getTodayCentreTotal(getUserCentreId(),"",""));
    	return prefix + "/centre";
	}
	
	/**
	 * 商户详情页面
	 * @param model
	 * @return
	 */
	@GetMapping("/centrePage")
    @RequiresPermissions("sys:user:centrePage")
    public String centrePage(Model model) {
    	model.addAttribute("centre", centreService.getByKey(getUserCentreId()));
    	model.addAttribute("rate", centreService.getRateByCentreId(getUserCentreId()));
    	model.addAttribute("amount", centreService.getAmountByCentreId(getUserCentreId()));
    	model.addAttribute("startDt",userService.getDefaultTime(getUserCentreId()).get("startDt").toString());
    	model.addAttribute("endDt",userService.getDefaultTime(getUserCentreId()).get("endDt").toString());
    	//model.addAttribute("money", userService.getTodayCentreTotal(getUserCentreId(),"",""));
    	return prefix + "/centre";
	}
	
	
	/**
	 * 平台查看商户明细平台
	 * @param model
	 * @return
	 */
	@GetMapping("/toLookCentrePage")
    @RequiresPermissions("sys:user:toLookCentrePage")
    public String toLookCentrePage(Model model) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		model.addAllAttributes(getCentreIdModelInfo());
    	model.addAttribute("startDt",df.format(DateUtils.getAddDayDate(new Date(), -1)).concat(" 20:30:00"));
    	model.addAttribute("endDt",df.format(new Date()).concat(" 20:05:00"));
    	return prefix + "/lookcentre";
	}
	
	
	/**
	 * 商户查询预计佣金明细
	 * @param centreId
	 * @param starDt
	 * @param endDt
	 * @return
	 */
	@GetMapping("/getTodayCentreTotal")
	@ResponseBody
	public PageUtils<OrderProductVo> getTodayCentreTotal(String starDt,String endDt,String baseId,
			String oppayStatus,String isafter,String opstatus,Integer offset, Integer limit) {
		if(StringUtils.isEmpty(starDt)) {
			starDt = "";
		}
		if(StringUtils.isEmpty(endDt)) {
			endDt = "";
		}
		return userService.getTodayCentreTotal(getUserCentreId(),starDt,endDt, baseId,oppayStatus,isafter,opstatus,offset, limit);
	}
	
	/**
	 * 商户查询预计佣金明细平台
	 * @param centreId
	 * @param starDt
	 * @param endDt
	 * @return
	 */
	@GetMapping("/getCentreTotal")
	@ResponseBody
	public PageUtils<OrderProductVo> getCentreTotal(Long   centreId,String starDt,String endDt,String baseId,
			String oppayStatus,String isafter,String opstatus,Integer offset, Integer limit) {
		if(StringUtils.isEmpty(starDt)) {
			starDt = "";
		}
		if(StringUtils.isEmpty(endDt)) {
			endDt = "";
		}
		return userService.getTodayCentreTotal(centreId,starDt,endDt, baseId,oppayStatus,isafter,opstatus,offset, limit);
	}
	
	/**
	 * 商户查询预计佣金总计平台
	 * @param centreId
	 * @param starDt
	 * @param endDt
	 * @return
	 */
	@GetMapping("/getTodayCentreCash")
	@ResponseBody
	public ResultVo getTodayCentreCash(Long   centreId,String starDt,String endDt,String baseId,String oppayStatus,String isafter,String opstatus) {
		ResultVo resultVo = new ResultVo();
		if(StringUtils.isEmpty(starDt)) {
			starDt = "";
		}
		if(StringUtils.isEmpty(endDt)) {
			endDt = "";
		}
		resultVo.put("vo",  userService.getTodayCash(centreId,starDt,endDt,baseId,oppayStatus,isafter,opstatus));
		return resultVo;
	}
	
	/**
	 * 商户查询预计佣金总计
	 * @param centreId
	 * @param starDt
	 * @param endDt
	 * @return
	 */
	@GetMapping("/getTodayCash")
	@ResponseBody
	public ResultVo getTodayCash(String starDt,String endDt,String baseId,String oppayStatus,String isafter,String opstatus) {
		ResultVo resultVo = new ResultVo();
		if(StringUtils.isEmpty(starDt)) {
			starDt = "";
		}
		if(StringUtils.isEmpty(endDt)) {
			endDt = "";
		}
		resultVo.put("vo",  userService.getTodayCash(getUserCentreId(),starDt,endDt,baseId,oppayStatus,isafter,opstatus));
		return resultVo;
	}
	
	

    /**
     * 账号列表
     * @param name
     * @param centreId
     * @param offset
     * @param limit
     * @return
     */
	@GetMapping("/list")
	@ResponseBody
    public PageUtils<SysUser> listUsers(String name,Long centreId, Integer offset, Integer limit) {
		// 查询列表数据
		Map<String,Object> params = new HashMap<>(2);
		if (StringUtils.isNotEmpty(name)) {
			params.put("name", name);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (PermisFlag.FLAG_CENTRE.equals(getUserFlag())) {
			params.put("centreId", getUserCentreId());
		}
		return userService.listUsers(params, offset, limit);
	}

	@RequiresPermissions("sys:user:add")
	@GetMapping("/add")
	public String add(Model model) {
		HashMap<String,Object> params = new HashMap<>(2);
		if (PermisFlag.FLAG_CENTRE.equals(getUserFlag())) {
			params.put("centreId", getUserCentreId());
			model.addAttribute("flag", PermisFlag.FLAG_CENTRE);
			Long centerId = getUserCentreId();
			model.addAttribute("centreId", centerId);
			//角色为
			model.addAttribute("teamList", memberService.listCenterTeamList(centerId));
		}else if (PermisFlag.FLAG_PLATFORM.equals(getUserFlag())) {
			params.put("centreId", PermisFlag.FLAG_PLATFORM);
			model.addAttribute("flag", PermisFlag.FLAG_PLATFORM);
			model.addAttribute("centreList", centreService.listAllCentres());
		}
		model.addAttribute("roles", roleService.listRoles(params));
		return prefix + "/add";
	}

	@RequiresPermissions("sys:user:edit")
	@GetMapping("/edit/{userId}")
	public String edit(Model model, @PathVariable("userId") Long userId) {
		SysUser user = userService.getUserById(userId);
		model.addAttribute("user", user);

		HashMap<String,Object> params = new HashMap<>(2);
		if (PermisFlag.FLAG_CENTRE.equals(getUserFlag())) {
			Long centerId = getUserCentreId();
			params.put("centreId", centerId);
			model.addAttribute("flag", PermisFlag.FLAG_CENTRE);
			//角色为
			model.addAttribute("teamId", user.getTeamId());
			model.addAttribute("teamList", memberService.listCenterTeamList(centerId));
		}
        List<SysRole> all = roleService.listRoles(params);
        List<SysRole> userRoles = roleService.listUserRoles(userId);

        for (SysRole role : all) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().equals(userRole.getRoleId())) {
                    role.setSign(Boolean.TRUE);
                    break;
                }
            }
        }
		model.addAttribute("roles", all);
		return prefix+"/edit";
	}

	@Log(module = "管理员管理", operation = "新增")
	@RequiresPermissions("sys:user:add")
	@PostMapping("/save")
	@ResponseBody
	public ResultVo save(SysUser user, String roleIds) {
		if (PermisFlag.FLAG_CENTRE.equals(getUserFlag())) {
			/**商户账号创建新账号，默认为该商户账号**/
			user.setCentreId(getUserCentreId());
			user.setFlag(PermisFlag.FLAG_CENTRE);
		}else {
			user.setFlag(user.getCentreId() == null? PermisFlag.FLAG_PLATFORM:PermisFlag.FLAG_CENTRE);
		}
		if (userService.saveUser(user,roleIds) > 0) {
			return ResultVo.ok();
		}
		return ResultVo.error();
	}

	@Log(module = "管理员管理", operation = "编辑")
	@RequiresPermissions("sys:user:edit")
	@PostMapping("/update")
	@ResponseBody
	public ResultVo update(SysUser user,String roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            String[] strings = roleIds.split(",");
            List<Long> rl = new ArrayList<>();
            for (int i=0;i< strings.length;i++) {
                if (StringUtils.isNotEmpty(strings[i])) {
                    rl.add(Long.parseLong(strings[i]));
                }
            }
            user.setRoleIds(rl);
        }

        if (userService.updateUser(user) > 0) {
            return ResultVo.ok();
        }
		return ResultVo.error();
	}



    /**
     * 个人资料修改
     * @param user
     * @return
     */
	@Log(module = "管理员管理", operation = "个人资料修改")
	@RequiresPermissions("sys:user:edit")
	@PostMapping("/updatePersonal")
	@ResponseBody
	public ResultVo updatePersonal(SysUser user) {
		if (userService.updateUser(user) > 0) {
			return ResultVo.ok();
		}
		return ResultVo.error();
	}

    /**
     * 账号删除
     * @param userId
     * @return
     */
	@Log(module = "管理员管理", operation = "删除")
	@RequiresPermissions("sys:user:remove")
	@PostMapping("/remove")
	@ResponseBody
	public ResultVo remove(Long userId,String flag) {

        if (userId == null) {
            return ResultVo.error();
        }
		if (userService.removeUser(userId,flag) > 0) {
			return ResultVo.ok();
		}
		return ResultVo.error();
	}


    /**
     * 检查用户名是否存在
     * @param name
     * @return
     */
	@PostMapping("/exit")
	@ResponseBody
	boolean exit(String name) {
		// 存在，不通过，false
		return !userService.checkExit(name);
	}

	@RequiresPermissions("sys:user:resetPwd")
	@GetMapping("/resetPwd/{userId}")
	public String resetPwd(@PathVariable("userId") Long userId, Model model) {
		model.addAttribute("userId", userId);
		model.addAttribute("userName", userService.getUserById(userId).getName());
		return prefix + "/reset_pwd";
	}

	@RequiresPermissions("sys:user:resetPwd")
	@PostMapping("/resetPwd")
	@ResponseBody
	public ResultVo resetPwd(SysUser sysUser) {
		if (sysUser == null) {
			return ResultVo.error();
		}
		sysUser.setDesc(getUsername());
		sysUser.setPassword(sysUser.getPassword());
		userService.resetPsw(sysUser);
		return ResultVo.ok();
	}


	@PostMapping("/personalRestPwd")
	@ResponseBody
	public ResultVo personalRestPwd(Long userId, String pwdOld, String pwdNew, String confirm_password) {
		if (userId== null || StringUtils.isEmpty(pwdOld) || StringUtils.isEmpty(pwdNew) || StringUtils.isEmpty(confirm_password)) {
			return ResultVo.error();
		}
		SysUser sysUser = userService.getUserById(userId);
		if (!sysUser.getPassword().equals(MD5Utils.encrypt(sysUser.getName(), pwdOld))) {
			return ResultVo.error("旧密码输入错误");
		}
		if (!pwdNew.equals(confirm_password)) {
			return ResultVo.error("两次密码输入不一致");
		}
		sysUser.setPassword(pwdNew);
		userService.resetPsw(sysUser);
		return ResultVo.ok();
	}

	
	  /**
     * 导出
     * @param vo
     * @param idOrName
     * @param response
     */
    @RequiresPermissions("sys:user:exportCentreLog")
    @GetMapping("/exportCentreLog")
	public void exportCentreLog(Long centreId, String starDt, String endDt, String baseId, String oppayStatus, String isafter, String opstatus, HttpServletResponse response) {
		List<List<Object>> resultData = new ArrayList<>();
		String[] head = { "序号", "订单ID","商品名称","成本价", "售价","订单总金额","数量", 
				"门店名", "门店佣金","创建时间", "商品区分","支付状态","状态"};
		resultData.add(0, Arrays.asList(head));
		if(StringUtils.isEmpty(starDt)) {
			starDt = "";
		}
		if(StringUtils.isEmpty(endDt)) {
			endDt = "";
		}
		  List<OrderProductVo> list =null;
		if(centreId==null) {
			list = userService.getTodayOrdList(getUserCentreId(),starDt,endDt,baseId,oppayStatus,isafter,opstatus);
		}else {
		   list = userService.getTodayOrdList(centreId,starDt,endDt,baseId,oppayStatus,isafter,opstatus);
		}
		int flag = 1;
		if (CollectionUtils.isNotEmpty(list)) {
			for (OrderProductVo obj : list) {
				if (obj == null) {
					continue;
				}
				String baseproductid = "";//商品区分
				String status = "";//状态
				if(obj.getBaseproductid()!=null &&  !obj.getBaseproductid().equals("")) {
					baseproductid = "平台商品";
				}else {
					baseproductid = "商户商品";
				}
				if (obj.getStatus().equals("1") ) {
					status =   "已付款";
                }else if (obj.getStatus().equals("2")) {
                	status =   "已发货";
                } else if (obj.getStatus().equals("3")) {
                	status =  "已收货";
                } else if (obj.getStatus().equals("4")) {
                	status =  "待退款";
                } else if (obj.getStatus(). equals("5")) {
                	status =  "售后中";
                }else if (obj.getStatus().equals("6")) {
                	status = "已完成";
                }
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				List<Object> row = new ArrayList<>();
				row.add(flag);
				row.add(obj.getId());
				row.add(obj.getProductName());
				row.add(obj.getCostprice());
				row.add(obj.getMarketprice());
				row.add(obj.getPrice());
				row.add(obj.getTotal());
				row.add(obj.getTnickname());
				row.add(obj.getHeadcommission());
				row.add(obj.getCreateTime()==null?"":obj.getCreateTime());
				row.add(baseproductid);
			    row.add(PayStatus.get(obj.getPayStatus()));
				row.add(status);
				resultData.add(row);
				flag++;
			}
		}
		String fileName = "站点预计佣金明细_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
		try {
			ExcelHelper.exportExcel(response, fileName, "站点预计佣金明细", resultData);
		} catch (IOException e) {
			logger.info("export achieve count error:{}", e.getMessage());
		}
	}
}
